
(function () {
    var that;
    var JoinActivity = function () {
        // -----------------全局变量----------------
        this.options = {
            app: undefined,             // 应用 初始化必传项
            activity: undefined,        // 活动 初始化必传项
            version: undefined,         // 版本 初始化必传项
            server: undefined,          // 服务 初始化必传项
            platform: undefined,        // 平台 初始化必传项

            host: location.origin,      // 接口请求域名，默认同域名
            isWxInit: false,            // 微信初始化
            isUserInit: false,          // 获取用户信息初始化
            isWxDebug: false,           // 是否开启微信debug调试

            token: undefined,           // token
            cyscid: undefined,          // 地址标识
            isInit: 0,                  // 初始化状态：0 未初始化 ； 1 初始化完成 ； 2 初始化失败
            appInfo: undefined,         // 应用信息 init/app
            activityInfo: undefined,    // 活动信息 init/activity
            clientInfo: undefined,      // 客户端信息    init/client
            userInfo: undefined,        // 用户信息

            ready: function() {},       // 初始化完成后执行
        };
        that = this;
    };
    JoinActivity.fn = JoinActivity.prototype = {
        // -----------------初始化----------------
        config: function(options)   {
            $.extend(this.options, options);
            var _this = this;
            if(!_this.options.app || !_this.options.activity || !_this.options.version || !_this.options.platform) {
                alert('初始化有四个必填项:\napp=' + _this.options.app + ';\nactivity=' + _this.options.activity + ';\nversion=' + _this.options.version + ';\nplatform=' + _this.options.platform);
                return false;
            }
            this.client.get("/landing/init", {}, function (res) {
                if(res.code === 10000) {
                    var info = res.data;
                    $.extend(_this.options, {
                        token: info.token,
                        cyscid: _this.utils.getQueryString("CYSCID"),
                        isInit: 1,
                        appInfo: info.app,
                        activityInfo: info.activity,
                        clientInfo: info.client
                    });
                    if(_this.options.isWxInit) {
                        if(_this.options.clientInfo.isWechat) {
                            _this.wx.init()
                        }else {
                            alert('初始化失败，需要在微信中打开');
                            return false;
                        }
                    }
                    if(_this.options.isUserInit) {
                        _this.user.getUserInfo(_this.options.ready);
                    }else {
                        _this.options.ready();
                    }
                }else {
                    $.extend(_this.data, { isInit: 2 });
                    alert(res.msg);
                }
            })
        },
        // -----------------ajax请求----------------
        client: {
            ajax: function (type, url, data, fun) {
                $.ajax({
                    type: type,
                    url: url,
                    data: data,
                    headers: {
                        "Authorization": that.options.token,
                        "APP": that.options.app,
                        "ACTIVITY": that.options.activity,
                        "VERSIONCODE": that.options.version,
                        "CYSCID": that.utils.getQueryString('CYSCID') || undefined
                    },
                    success: function(res) {
                        fun(res)
                    }
                })
            },
            get: function (url, data, fun) {
                this.ajax('GET', that.options.host + '/' + that.options.platform + url, data, fun);
            },
            post: function (url, data, fun) {
                this.ajax('POST', that.options.host + '/' + that.options.platform +  url, data, fun);
            },
        },
        // -----------------用户业务----------------
        user: {
            url: {
                userInfoPath: "/user/info",      // 用户详情
                phoneCode: '/core/zhpt/sendcode',    // 登陆发送手机号验证码
                core: function() { return  '/core/login/' + that.options.app + '/' + that.options.activity + '/' + that.options.version },
            },
            // 获取用户信息
            getUserInfo: function(fun) {
                that.client.get(this.url.userInfoPath, {}, function(res) {
                    fun(res);
                    if(res.code !== 10000) {
                        that.options.userInfo = res.data;
                    }else {
                        console.log('用户还没有登陆');
                    }
                })
            },
            // 获取验证码
            getCode: function(phone, fun) {
                that.client.post(this.url.phoneCode, {
                    phone: phone
                }, function(res) {
                    fun ? fun(res) : alert(res.code === 10000 ? '验证码发送成功' : res.message);
                });
            },
            // 手机号与验证码登陆
            loginPhone: function(phone, code, fun) {
                that.client.post(this.url.core() + '/phonelogin', {
                    phone: phone,
                    code: code
                }, function(res) {
                    fun ? fun(res) : res.code === 10000 ? location.reload() : alert(res.message);
                });
            },
            // 登陆（星际战甲）
            loginXJZJ: function(back) {
                that.utils.cookie.del("CASGTC");
                return that.options.host + "/" + that.options.platform + this.url.core() + "?callback=" + encodeURI(back || location.href);
            },
            // 登出
            logout: function (fun) {
                that.client.post(this.url.core() + '/logout', {}, function () {
                    fun || location.reload();
                });
            }
        },
        // -----------------工具类----------------
        utils: {
            // 截取url参数
            getQueryString: function(name) {
                var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if(r!=null)return  unescape(r[2]); return null;
            },
            // 是否是微信浏览器
            isWechat: function() {
                var ua = window.navigator.userAgent.toLowerCase();
                return ua.match(/MicroMessenger/i) == 'micromessenger'
            },
            // cookie操作
            cookie: {
                get: function(cname) {
                    var name = cname + "=";
                    var ca = document.cookie.split(';');
                    for(var i=0; i<ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0)==' ') c = c.substring(1);
                        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
                    }
                    return "";
                },
                set: function(cname, cvalue, exdays) {
                    var d = new Date();
                    d.setTime(d.getTime() + (exdays*24*60*60*1000));
                    var expires = "expires="+d.toUTCString();
                    document.cookie = cname + "=" + cvalue + "; " + expires;
                },
                del: function(name) {
                    this.set(name, "", -1);
                }
            }
        },
        // -----------------微信业务----------------
        wx: {
            // 微信初始化
            init: function() {
                $.ajax({
                    url: location.origin + "/wechat/web/" + that.options.activityInfo.wxId + "/config",
                    success: function(data) {
                        if(data.config) {
                            $.getScript("https://res.wx.qq.com/open/js/jweixin-1.4.0.js", function () {
                                wx.config({
                                    debug: that.options.isWxDebug ,       // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                                    appId: data.config.appId,           // 必填，公众号的唯一标识
                                    timestamp: data.config.timestamp,   // 必填，生成签名的时间戳
                                    nonceStr: data.config.nonceStr,     // 必填，生成签名的随机串
                                    signature: data.config.signature,   // 必填，签名，见附录1
                                    jsApiList: [                        // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                                        "onMenuShareTimeline",
                                        "onMenuShareAppMessage",
                                        "onMenuShareQQ",
                                        "onMenuShareWeibo",
                                        "hideMenuItems",
                                        "hideAllNonBaseMenuItem",
                                        "onMenuShareQZone"
                                    ]
                                });
                            })
                        }else {
                            alert('微信初始化失败，' + data.msg);
                        }
                    }
                });
            },
            // 分享
            share: function(options) {
                var _options = {
                    type: "link",
                    shareList: [
                        "onMenuShareTimeline",      // 分享到朋友圈
                        "onMenuShareAppMessage",    // 分享给朋友
                        "onMenuShareQQ",            // 分享到QQ
                        "onMenuShareWeibo",         // 分享到腾讯微博
                        "onMenuShareQZone"          // 分型到QQ空间
                    ]
                };
                _options = $.extend(_options, options);
                var list = _options.shareList;
                delete _options["shareList"];
                wx.ready(function() {
                    for(var i in list) {
                        var shareType = list[i];
                        if($.isFunction(wx[shareType])) {
                            wx[shareType](_options);
                        }
                    }
                })
            }
        }
    };
    window.ja = new JoinActivity();
}());
